package st.lib.base.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;

/**
 * @author zhangyu
 * @date 2018/11/1
 */

public class InterceptRadioGroup extends RadioGroup {
    private int checkId;
    private OnInterceptListener mInterceptListener;

    public InterceptRadioGroup(Context context) {
        super(context);
    }

    public InterceptRadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setInterceptListener(OnInterceptListener listener) {
        mInterceptListener = listener;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            RadioButton child = (RadioButton) getChildAt(i);
            int x = (int) ev.getX();
            int y = (int) ev.getY();
            int left = child.getLeft();
            int right = child.getRight();
            int top = child.getTop();
            int bottom = child.getBottom();
            if (x < right && x > left && y > top && y < bottom) {
                checkId = child.getId();
                break;
            }
        }
        if (getCheckedRadioButtonId() != checkId) {
            if (mInterceptListener != null) {
                mInterceptListener.checked(checkId);
            }
        }
        return true;
    }

    public interface OnInterceptListener {
        void checked(int id);
    }

}
